﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using H2.Streams;

namespace Mystery.SCNR
{
    public class AIZone
    {
        public const int Offset = 360;
        public const int ChunkSize = 56;

        public short BSPOrigin;

        public static AIZone[] Read(MapStream map, int scnrOffset)
        {
            AIZone[] zones = new AIZone[map.ReadReflexiveAt(scnrOffset + Offset)];
            int startOffset = (int)map.Position;

            for (int i = 0; i < zones.Length; ++i)
            {
                int chunkStartOffset = startOffset + (i * ChunkSize);

                AIZone aiZone = new AIZone();
                zones[i] = aiZone;

                aiZone.BSPOrigin = map.ReadInt16At(chunkStartOffset + 36, false);
            }

            return zones;
        }

        public static void Update(AIZone[] zones, int selectedBSPIndex)
        {
            for (int i = 0; i < zones.Length; ++i)
            {
                AIZone aiz = zones[i];
                if (aiz.BSPOrigin == selectedBSPIndex) aiz.BSPOrigin = 0;
                else if (aiz.BSPOrigin == 0) aiz.BSPOrigin = (short)selectedBSPIndex;
            }
        }

        public static void Write(MapStream map, int scnrOffset, AIZone[] zones)
        {
            map.ReadReflexiveAt(scnrOffset + Offset);
            int startOffset = (int)map.Position;

            for (int i = 0; i < zones.Length; ++i)
            {
                int chunkStartOffset = startOffset + (i * ChunkSize);

                AIZone aiZone = zones[i];

                map.WriteAt(chunkStartOffset + 36, aiZone.BSPOrigin, false);
            }
        }
    }
}
